package main

//导入gin
import (
	"github.com/gin-gonic/gin"
	"apiserver/router"
	"net/http"
	"github.com/zxmrlc/log"
	"time"
	"errors"
	"github.com/spf13/pflag"
	"github.com/spf13/viper"
	"apiserver/config"
	"apiserver/model"
)

var(
	cfg = pflag.StringP("config", "c","","apiserver config file path.")
)

func main() {
	//生成实例
	g := gin.Default()

	//解析配置文件 =>如果没有解析使用默认配置文件
	pflag.Parse()

	//加载配置文件
	//config.Init()
	if err:=config.Init(*cfg); err != nil{
		panic(err)
	}
	
	//加载数据库连接
	model.DB.Init()
	defer model.DB.Close()

	//声明了一个路由/及对应的处理函数
	router.Load(g)

	//调用协程函数，
	go func() {
		if err := pingServer(); err != nil {
			log.Fatal("The router has no response, or it might took too long to start up.", err)
		}
		log.Infof("The router has been deployed successfully.")
	}()

	// 让应用运行在本地服务器上，默认监听端口是8080
	//g.Run(":8000") 	//listen  and  server on 0.0.0.0:8000
	g.Run(viper.GetString("addr"))
}


//pingServer pings the http server to make sure the router is working.
func pingServer() error {
	//如果函数正常运行  返回nill
	//如果函数出错了  error
	for i := 0; i < 10; i++ {
		// 请求/sd/health => Get返回值有两个
		resp, err := http.Get("http://127.0.0.1:8000" + "/sd/health")
		log.Infof("Waiting for the router, retry in 1 second.")
		// 如果返回200，则表示启动成功，直接返回nil
		if err == nil && resp.StatusCode == 200 {
			return nil
		}
		
		// 否则1秒后重试
		log.Infof("Waiting for the router, retry in 1 second.")
		time.Sleep(time.Second)
	}
	// 尝试10次，均失败则返回一个错误
	return errors.New("Cannot connect to the router.")
}
